package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @param startDate
     * @param endDate
     * @return
     */
    public TurnoverReportVO getTurnoverReport(LocalDate startDate, LocalDate endDate) {
        List<BigDecimal> amountList = new ArrayList<>();
        List<LocalDate> dateList = getDateList(startDate, endDate);
        // 循环查询每天的营业额
        for (LocalDate date : dateList) {
            BigDecimal amount = orderMapper.selectOrderAmountSum(date);
            // 没有时,插入0
            if (amount == null) {
                amount = BigDecimal.ZERO;
            }
            amountList.add(amount);
        }
        log.info("dateList数据为: {}", dateList);
        log.info("dateList数据为: {}", StringUtils.join(dateList, ","));
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(StringUtils.join(dateList, ","));
        turnoverReportVO.setTurnoverList(StringUtils.join(amountList, ","));
        return turnoverReportVO;
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserReport(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDateList(begin, end);
        List<String> userCountList = new ArrayList<>();
        List<String> newAddCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
             // 查询当天前一天的用户数量,计算新增
            String yesUserCount = orderMapper.selectUserCount(date.minusDays(1));
            String userCount = orderMapper.selectUserCount(date);
            Integer sub = Integer.parseInt(userCount) - Integer.parseInt(yesUserCount);
            if (sub < 0) {
                sub = 0;
            }
            String newAddCount = String.valueOf(sub);
            newAddCountList.add(newAddCount);
            userCountList.add(userCount);
        }
        UserReportVO userReportVO = UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(userCountList, ","))
                .newUserList(StringUtils.join(newAddCountList,","))
                .build();
        return userReportVO;
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrderReport(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDateList(begin, end);
        List<String> orderCountList = new ArrayList<>();
        List<String> validOrderCountList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;
        for (LocalDate date : dateList) {
            // 查询当天订单数量
            Integer orderCount = orderMapper.countAll(date);
            // 查询当天有效订单数量
            Integer validCount = orderMapper.countVaildStatus(5, date);
            orderCountList.add(String.valueOf(orderCount));
            validOrderCountList.add(String.valueOf(validCount));
            totalOrderCount += orderCount;
            validOrderCount += validCount;
        }
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate((double) validOrderCount / totalOrderCount)
                .build();
        return orderReportVO;
    }

    /**
     * 销售top10统计
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getSalesTop10Report(LocalDate begin, LocalDate end) {
        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        List<GoodsSalesDTO> goodSaleList = orderDetailMapper.getGoodSale();
        // 将goodsaleList中的name和number分别放入两个list中
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        for (GoodsSalesDTO goodsSalesDTO : goodSaleList) {
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getTotal());
        }
        salesTop10ReportVO.setNameList(StringUtils.join(nameList, ","));
        salesTop10ReportVO.setNumberList(StringUtils.join(numberList, ","));
        return salesTop10ReportVO;
    }

    /**
     * 导出运行数据报表excel
     * @param response
     */
    public void exportExcel(HttpServletResponse response) {
        //查询营业数据，
        LocalDate startDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(startDate, LocalTime.MIN), LocalDateTime.of(endDate, LocalTime.MAX));
        //通过POI将数据写入excel
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            // 填充数据
            XSSFSheet sheet1 = excel.getSheet("sheet1");
            sheet1.getRow(1).getCell(1).setCellValue("时间：" + startDate + "至" + endDate);
            sheet1.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            sheet1.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            sheet1.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            sheet1.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            sheet1.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = startDate.plusDays(i);
                BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                sheet1.getRow(7 + i).getCell(1).setCellValue(date.toString());
                sheet1.getRow(7 + i).getCell(2).setCellValue(businessData1.getTurnover());
                sheet1.getRow(7 + i).getCell(3).setCellValue(businessData1.getValidOrderCount());
                sheet1.getRow(7 + i).getCell(4).setCellValue(businessData1.getOrderCompletionRate());
                sheet1.getRow(7 + i).getCell(5).setCellValue(businessData1.getUnitPrice());
                sheet1.getRow(7 + i).getCell(6).setCellValue(businessData1.getNewUsers());
            }

            //通过输出流下载excel
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            //关闭资源
            outputStream.close();
            excel.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    //将计算时间起止的代码封装
    private List<LocalDate> getDateList(LocalDate startDate, LocalDate endDate) {
        // 获取从开始到结束之间的日期列表
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(startDate);
        while (!startDate.equals(endDate)) {
            startDate = startDate.plusDays(1);
            dateList.add(startDate);
        }
        return dateList;
    }
}
